package damas.gui;

import damas.logicaYcontroladores.DamasLogica;
import damas.modelo.DamasModelo;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import utils.Pair;

/**
 * @author Sim�n Emmanuel Guti�rrez Brida
 * @version 0.1
 */
public class DamasGui extends javax.swing.JFrame implements ActionListener, MouseListener
{
    private static final String RAWTYPES = "rawtypes";
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private RenderizadorTablero render;
    private DamasLogica logica;

    /**
     * Creates new form DamasGui
     */
    public DamasGui() {}

    public void init()
    {
        render = new RenderizadorTablero();
        initComponents();
        this.setVisible(true);
        this.setEnabled(true);
        this.board.setEnabled(false);
        this.paintDisabledBoard();
    }

    public void definirLogica(DamasLogica logica)
    {
        this.logica = logica;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {

        mainPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        board = new javax.swing.JTable();
        jugador2Label = new javax.swing.JLabel();
        jugador1Label = new javax.swing.JLabel();
        color1Label = new javax.swing.JLabel();
        color2Label = new javax.swing.JLabel();
        comidas1Label = new javax.swing.JLabel();
        comidas2Label = new javax.swing.JLabel();
        menuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        nuevoMenuItem = new javax.swing.JMenuItem();
        frenarMenuItem = new javax.swing.JMenuItem();
        salirMenuItem = new javax.swing.JMenuItem();
        preferenciasMenu = new javax.swing.JMenu();
        preferenciasMenuItem = new javax.swing.JMenuItem();
        ayudaMenu = new javax.swing.JMenu();
        acercaMenuItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setLocationByPlatform(true);
        setResizable(false);

        board.setModel(new javax.swing.table.DefaultTableModel(
                           new Object [][]
        {
            {null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null}
        },
        new String []
        {
            "", "", "", "", "", "", "", ""
        }
                       )
        {
            /**
             *
             */
            private static final long serialVersionUID = 1L;
            @SuppressWarnings(RAWTYPES)
            Class[] types = new Class []
            {
                java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean []
            {
                false, false, false, false, false, false, false, false
            };

            @SuppressWarnings(RAWTYPES)
            public Class getColumnClass(int columnIndex)
            {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex)
            {
                return canEdit [columnIndex];
            }
        });
        board.setDefaultRenderer(Integer.class, this.render);
        board.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
        board.setAutoscrolls(false);
        board.setColumnSelectionAllowed(true);
        board.setDoubleBuffered(true);
        board.setFillsViewportHeight(true);
        board.setOpaque(false);
        board.setRowHeight(72);
        board.setRowSelectionAllowed(false);
        board.setShowHorizontalLines(false);
        board.setShowVerticalLines(false);
        board.addMouseListener(this);
        jScrollPane1.setViewportView(board);

        jugador2Label.setText("jugador2");

        jugador1Label.setText("jugador1");

        color1Label.setText("COLOR");

        color2Label.setText("COLOR");

        comidas1Label.setText("XXX");

        comidas2Label.setText("XXX");

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                      .addContainerGap()
                      .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 645, Short.MAX_VALUE)
                                .addGroup(mainPanelLayout.createSequentialGroup()
                                          .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                                  .addComponent(jugador2Label, javax.swing.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
                                                  .addComponent(jugador1Label, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                          .addGap(18, 18, 18)
                                          .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                                  .addComponent(color1Label, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
                                                  .addComponent(color2Label, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                          .addGap(18, 18, 18)
                                          .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                                  .addComponent(comidas1Label, javax.swing.GroupLayout.DEFAULT_SIZE, 64, Short.MAX_VALUE)
                                                  .addComponent(comidas2Label, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                          .addGap(0, 0, Short.MAX_VALUE)))
                      .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                      .addGap(0, 44, Short.MAX_VALUE)
                      .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jugador1Label)
                                .addComponent(color1Label)
                                .addComponent(comidas1Label))
                      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                      .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jugador2Label)
                                .addComponent(color2Label)
                                .addComponent(comidas2Label))
                      .addGap(18, 18, 18)
                      .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 589, javax.swing.GroupLayout.PREFERRED_SIZE)
                      .addContainerGap())
        );

        fileMenu.setMnemonic('f');
        fileMenu.setText("File");

        nuevoMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        nuevoMenuItem.setMnemonic('N');
        nuevoMenuItem.setText("Nuevo");
        nuevoMenuItem.addActionListener(this);
        fileMenu.add(nuevoMenuItem);

        frenarMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.CTRL_MASK));
        frenarMenuItem.setMnemonic('D');
        frenarMenuItem.setText("Detener");
        frenarMenuItem.addActionListener(this);
        fileMenu.add(frenarMenuItem);

        salirMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
        salirMenuItem.setMnemonic('S');
        salirMenuItem.setText("Salir");
        salirMenuItem.addActionListener(this);
        fileMenu.add(salirMenuItem);

        menuBar.add(fileMenu);

        preferenciasMenu.setMnemonic('e');
        preferenciasMenu.setText("Edit");

        preferenciasMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK));
        preferenciasMenuItem.setMnemonic('P');
        preferenciasMenuItem.setText("Preferencias");
        preferenciasMenuItem.addActionListener(this);
        preferenciasMenu.add(preferenciasMenuItem);

        menuBar.add(preferenciasMenu);

        ayudaMenu.setMnemonic('h');
        ayudaMenu.setText("Ayuda");

        acercaMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK));
        acercaMenuItem.setMnemonic('A');
        acercaMenuItem.setText("Acerca de");
        acercaMenuItem.addActionListener(this);
        ayudaMenu.add(acercaMenuItem);

        menuBar.add(ayudaMenu);

        setJMenuBar(menuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }

    // Code for dispatching events from components to event handlers.

    public void actionPerformed(java.awt.event.ActionEvent evt)
    {
        if (evt.getSource() == salirMenuItem)
        {
            DamasGui.this.salirMenuItemActionPerformed(evt);
        }
        else if (evt.getSource() == nuevoMenuItem)
        {
            DamasGui.this.nuevoMenuItemActionPerformed(evt);
        }
        else if (evt.getSource() == frenarMenuItem)
        {
            DamasGui.this.frenarMenuItemActionPerformed(evt);
        }
        else if (evt.getSource() == preferenciasMenuItem)
        {
            DamasGui.this.preferenciasMenuItemActionPerformed(evt);
        }
        else if (evt.getSource() == acercaMenuItem)
        {
            DamasGui.this.acercaMenuItemActionPerformed(evt);
        }
    }

    public void mouseClicked(java.awt.event.MouseEvent evt)
    {
    }

    public void mouseEntered(java.awt.event.MouseEvent evt)
    {
    }

    public void mouseExited(java.awt.event.MouseEvent evt)
    {
    }

    public void mousePressed(java.awt.event.MouseEvent evt)
    {
    }

    public void mouseReleased(java.awt.event.MouseEvent evt)
    {
        if (evt.getSource() == board)
        {
            DamasGui.this.boardMouseReleased(evt);
        }
    }// </editor-fold>//GEN-END:initComponents

    private void salirMenuItemActionPerformed(java.awt.event.ActionEvent evt)  //GEN-FIRST:event_salirMenuItemActionPerformed
    {
        System.exit(0);
    }//GEN-LAST:event_salirMenuItemActionPerformed


    private Pair<Integer, Integer> ultimaPosicion = null;
    private void boardMouseReleased(java.awt.event.MouseEvent evt)  //GEN-FIRST:event_boardMouseReleased
    {
        int row = this.board.rowAtPoint(evt.getPoint());
        int col = this.board.columnAtPoint(evt.getPoint());
        Pair<Integer, Integer> posicionActual = new Pair<Integer, Integer>(row, col);
        int valorCelda = (Integer)this.board.getValueAt(posicionActual.getFirstElem(), posicionActual.getSecondElem());
        if (ultimaPosicion == null)
        {
            if (hayFicha(valorCelda))
            {
                ultimaPosicion = posicionActual;
            }
            else
            {
                ultimaPosicion = null;
            }
        }
        else
        {
            if ((valorCelda == DamasModelo.FONDO_BLANCO) || (valorCelda == DamasModelo.FONDO_NEGRO))
            {
                this.logica.mover(ultimaPosicion, posicionActual);
            }
            else
            {
                ultimaPosicion = null;
            }
        }
    }//GEN-LAST:event_boardMouseReleased

    private void nuevoMenuItemActionPerformed(java.awt.event.ActionEvent evt)  //GEN-FIRST:event_nuevoMenuItemActionPerformed
    {
        this.logica.nuevoJuego();
    }//GEN-LAST:event_nuevoMenuItemActionPerformed

    private void frenarMenuItemActionPerformed(java.awt.event.ActionEvent evt)  //GEN-FIRST:event_frenarMenuItemActionPerformed
    {
        this.logica.frenarPartida();
    }//GEN-LAST:event_frenarMenuItemActionPerformed

    private void preferenciasMenuItemActionPerformed(java.awt.event.ActionEvent evt)  //GEN-FIRST:event_preferenciasMenuItemActionPerformed
    {
        DamasPreferencias prefs = new DamasPreferencias();
        prefs.definirLogica(this.logica);
        this.setFocusable(false);
        this.setEnabled(false);
        prefs.start();
    }//GEN-LAST:event_preferenciasMenuItemActionPerformed

    private void acercaMenuItemActionPerformed(java.awt.event.ActionEvent evt)  //GEN-FIRST:event_acercaMenuItemActionPerformed
    {
        DamasAcercaDe acerca = new DamasAcercaDe(this, true);
        acerca.setVisible(true);
    }//GEN-LAST:event_acercaMenuItemActionPerformed



    /**
     * @param args the command line arguments
     */
    public static void main(String args[])
    {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try
        {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
            {
                if ("Nimbus".equals(info.getName()))
                {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        }
        catch (ClassNotFoundException ex)
        {
            java.util.logging.Logger.getLogger(DamasGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (InstantiationException ex)
        {
            java.util.logging.Logger.getLogger(DamasGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (IllegalAccessException ex)
        {
            java.util.logging.Logger.getLogger(DamasGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (javax.swing.UnsupportedLookAndFeelException ex)
        {
            java.util.logging.Logger.getLogger(DamasGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable()
        {

            public void run()
            {
                new DamasGui().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem acercaMenuItem;
    private javax.swing.JMenu ayudaMenu;
    private javax.swing.JTable board;
    private javax.swing.JLabel color1Label;
    private javax.swing.JLabel color2Label;
    private javax.swing.JLabel comidas1Label;
    private javax.swing.JLabel comidas2Label;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenuItem frenarMenuItem;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel jugador1Label;
    private javax.swing.JLabel jugador2Label;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem nuevoMenuItem;
    private javax.swing.JMenu preferenciasMenu;
    private javax.swing.JMenuItem preferenciasMenuItem;
    private javax.swing.JMenuItem salirMenuItem;
    // End of variables declaration//GEN-END:variables


    public void update(DamasModelo modelo)
    {
        for (int row = 0; row < 8; row++)
        {
            for (int col = 0; col < 8; col++)
            {
                int fondo = modelo.fondoEn(row, col);
                int ficha = modelo.fichaEn(row, col);
                this.board.setValueAt(fondo * (ficha == 0 ? 1 : ficha), row, col);
            }
        }
        this.comidas1Label.setText(Integer.toString(getColor1Label().getText().compareToIgnoreCase("rojas") == 0 ? modelo.fichasComidas(DamasModelo.ROJA) : modelo.fichasComidas(DamasModelo.NEGRA)));
        this.comidas2Label.setText(Integer.toString(getColor2Label().getText().compareToIgnoreCase("rojas") == 0 ? modelo.fichasComidas(DamasModelo.ROJA) : modelo.fichasComidas(DamasModelo.NEGRA)));
        getColor1Label().setForeground(null);
        getColor2Label().setForeground(null);
        if (modelo.esMax())
        {
            if (getColor1Label().getText().compareToIgnoreCase("rojas") == 0)
            {
                //le toca al jugador 1
                getColor1Label().setForeground(Color.blue);
            }
            else
            {
                //le toca al jugador 2
                getColor2Label().setForeground(Color.blue);
            }

        }
        else
        {
            if (getColor1Label().getText().compareToIgnoreCase("negras") == 0)
            {
                //le toca al jugador 1
                getColor1Label().setForeground(Color.blue);
            }
            else
            {
                //le toca al jugador 2
                getColor1Label().setForeground(Color.blue);
            }
        }
        this.board.updateUI();
        if (modelo.juegoTermino())
        {
            if (modelo.ganoMax())
            {
                resultado(true, false, modelo.esHumano(DamasModelo.ROJA), modelo.esHumano(DamasModelo.NEGRA), modelo.nombreJugador(DamasModelo.ROJA), modelo.nombreJugador(DamasModelo.NEGRA));
            }
            else if (modelo.ganoMin())
            {
                resultado(false, true, modelo.esHumano(DamasModelo.ROJA), modelo.esHumano(DamasModelo.NEGRA), modelo.nombreJugador(DamasModelo.ROJA), modelo.nombreJugador(DamasModelo.NEGRA));
            }
            else
            {
                resultado(true, true, modelo.esHumano(DamasModelo.ROJA), modelo.esHumano(DamasModelo.NEGRA), modelo.nombreJugador(DamasModelo.ROJA), modelo.nombreJugador(DamasModelo.NEGRA));
            }
            this.logica.frenarPartida();
        }
    }

    private void resultado(boolean ganoMax, boolean ganoMin, boolean rojoEsHumano, boolean negroEsHumano, String nrojo, String nnegro)
    {
        boolean unSoloJugador = rojoEsHumano ^ negroEsHumano;
        DialogoFinDeJuego dialogoFin;
        if (ganoMax && ganoMin)
        {
            dialogoFin = new DialogoFinDeJuego(new ImageIcon(System.class.getResource("/imagenes/empataste120x120.jpg")), "EMPATARON!!!");
        }
        else
        {
            if (unSoloJugador)
            {
                if (rojoEsHumano && ganoMax)
                {
                    dialogoFin = new DialogoFinDeJuego(new ImageIcon(System.class.getResource("/imagenes/ganaste120x120.jpg")), "GANASTE!!!");
                }
                else if (negroEsHumano && ganoMin)
                {
                    dialogoFin = new DialogoFinDeJuego(new ImageIcon(System.class.getResource("/imagenes/ganaste120x120.jpg")), "GANASTE!!!");
                }
                else
                {
                    dialogoFin = new DialogoFinDeJuego(new ImageIcon(System.class.getResource("/imagenes/perdiste120x120.jpg")), "PERDISTE!!!");
                }
            }
            else
            {
                if (ganoMax)
                {
                    dialogoFin = new DialogoFinDeJuego(new ImageIcon(System.class.getResource("/imagenes/ganaste120x120.jpg")), nrojo);
                }
                else
                {
                    dialogoFin = new DialogoFinDeJuego(new ImageIcon(System.class.getResource("/imagenes/ganaste120x120.jpg")), nnegro);
                }
            }
        }
        this.setEnabled(false);
        this.setFocusable(false);
        dialogoFin.setFather(this);
        dialogoFin.setVisible(true);
    }

    private void paintDisabledBoard()
    {
        for (int row = 0; row < 8; row++)
        {
            for (int col = 0; col < 8; col++)
            {
                this.board.setValueAt(0, row, col);
            }
        }
    }

    public void habilitarTablero()
    {
        this.board.setEnabled(true);
        this.board.setVisible(true);
    }

    public void deshabilitarTablero()
    {
        this.board.setEnabled(false);
        this.board.setVisible(false);
    }

    public void habilitarInteraccionTablero(boolean habilitar)
    {
        this.board.setEnabled(habilitar);
    }

    public void habilitarPreferencias(boolean habilitar)
    {
        this.preferenciasMenuItem.setEnabled(habilitar);
    }

    public JLabel getColor1Label()
    {
        return color1Label;
    }

    public JLabel getColor2Label()
    {
        return color2Label;
    }

    public JLabel getJugador1Label()
    {
        return jugador1Label;
    }

    public JLabel getJugador2Label()
    {
        return jugador2Label;
    }

    private boolean hayFicha(int valorCelda)
    {
        boolean fichaSimpleRoja  = valorCelda == DamasModelo.ROJA * DamasModelo.FONDO_BLANCO || valorCelda == DamasModelo.ROJA * DamasModelo.FONDO_NEGRO;
        boolean fichaSimpleNegra = valorCelda == DamasModelo.NEGRA * DamasModelo.FONDO_BLANCO || valorCelda == DamasModelo.NEGRA * DamasModelo.FONDO_NEGRO;
        boolean fichaDobleRoja   = valorCelda == DamasModelo.ROJA * DamasModelo.FONDO_BLANCO * DamasModelo.DAMA || valorCelda == DamasModelo.ROJA * DamasModelo.FONDO_NEGRO * DamasModelo.DAMA;
        boolean fichaDobleNegra  = valorCelda == DamasModelo.NEGRA * DamasModelo.FONDO_BLANCO * DamasModelo.DAMA || valorCelda == DamasModelo.NEGRA * DamasModelo.FONDO_NEGRO * DamasModelo.DAMA;
        return fichaSimpleRoja || fichaSimpleNegra || fichaDobleRoja || fichaDobleNegra;
    }

}
